
/*
* Copyright (C) 2020 ~ 2024 chaigec All Rights Reserved.
*
* Author:     chaigec <chaigec@163.com>
* Maintainer: chaigec <chaigec@163.com>

 * Use of this source code is governed by MIT license that can be found in the
 * LICENSE file in the root of the source tree. All contributing project authors
 * may be found in the AUTHORS file in the root of the source tree.
*/

#ifndef MK_EVENT_H
#define MK_EVENT_H
#include "MkUtil/MkTypes.h"
#include "MkUtil/MkRwLock.h"
#include "MkUtil/MkTime.h"
#include "MkUtil/MkThread.h"
#include <atomic>
#ifndef _WIN32
#include <sys/epoll.h>
#endif

typedef MkFunction<void()> PipTaskCallback;
typedef MkFunction<void(Uint32)> MkEventCallback;
class CMkPipe;
class MkApi CMkEvent
{
public:
    typedef enum _mk_event
    {
        EventNone = 0,
        EventRead = 1,
        EventWrite = 1 << 1,
        EventError = 1 << 2,
        EventEt = 1 << 3,
        EventRemove = 1 << 4
    }MkEvent;
private:
    typedef struct _eventer_param
    {
        MkEventCallback  EventCb;
        Uint32           Event;
    }MkEventerParam;
    typedef MkUnorderedMap<SOCKET, MkEventerParam>       MapEventer;  //value MkSocketItem
public:
    CMkEvent();
    Uint32 AddEventer(SOCKET Sock, Uint32 Event, const MkEventCallback& EventCb);
    Uint32 ModifyEventer(SOCKET Sock, Uint32 Event);
    Uint32 AddPipTask(PipTaskCallback Cb, BOOL bFirst = FALSE);
    Uint32 GetDispatchThreadId() { return m_DispatchThreadId; }
protected:
    void DoLoop();
private:
    Uint32 DeleteEventer(SOCKET Sock);
    friend class CMkSocket;
private:
    Uint32 Start();
    Uint32 Stop();
    virtual ~CMkEvent();
    Uint32 GetScore() const { return m_Score; }
    friend class CMkEventPool;
#ifndef _WIN32
    Uint32 MkEventToEpollEvent(Uint32 Event);
#endif // !_WIN32

private:
    BOOL                            m_bRun;
    CMkThread                       m_EventThread;
    Uint32                          m_Score;
    Uint32                          m_DispatchThreadId;
    CMkPipe                         *m_pPip;
#ifndef _WIN32
    int                             m_EpollFd;
    struct epoll_event              *m_pEvents;
#endif
    MapEventer                      m_MapEventer;
    CMkRwLock                       m_PipTaskLock;
    MkList<PipTaskCallback>         m_ListPipTask;
    BOOL                            m_HasRemoved;
};
#endif
